package com.firexxx.vp.utils;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.math3.linear.Array2DRowRealMatrix;
import org.apache.commons.math3.linear.RealMatrix;

import java.util.List;

/**
 * @Package: com.lizhe.test.vprTest
 * @author: fjli2@iflytek.com
 * @date: 2018/10/9 21:00
 */
public class MatrixUtil {

    public static RealMatrix multiply(RealMatrix matrixOne, RealMatrix matrixTwo){
        RealMatrix resultMatrix = matrixOne.multiply(matrixTwo);
        return resultMatrix;
    }

    public static double[] connectArry(float[] plpArr, float[] pnccArr){
        if (plpArr == null || plpArr.length <= 0 || pnccArr == null || pnccArr.length <= 0){
            return null;
        }

        double[] resultArr = new double[plpArr.length + pnccArr.length];
        for (int i=0; i < plpArr.length; i++){
            resultArr[i] = plpArr[i];
        }

        for (int m=0; m < pnccArr.length; m++){
            resultArr[plpArr.length + m] = pnccArr[m];
        }

        return resultArr;
    }

    public static void splitArry(double[] combinedArr, float[] plpArr, float[] pnccArr){
        if (combinedArr == null || combinedArr.length <= 0) {
            return;
        }

        for (int i = 0; i < plpArr.length; i++){
            plpArr[i] = (float) combinedArr[i];
        }

        for (int i=0; i < pnccArr.length; i++){
            pnccArr[i] = (float) combinedArr[i + plpArr.length];
        }
    }

    public static float getCosineDistance(double[] source, double[] target) {
        int i;
        int length = source.length;
        float sum=0;
        float sum_x=0;
        float sum_y=0;
        for (i=0; i < length;i++){
            sum    += source[i]*target[i];
            sum_x  += source[i]*source[i];
            sum_y  += target[i]*target[i];
        }
        sum_x = (float)Math.sqrt(sum_x);
        sum_y = (float)Math.sqrt(sum_y);
        sum = sum/(sum_x*sum_y);
        return sum;
    }

    public static RealMatrix getLppMatrix(String filePath,int row, int col, String format){
        List<String> strList = FileUtil.readFormatedFileByLines(filePath,format);
        double[][] doubleArr = new double[row][col];
        if (CollectionUtils.isNotEmpty(strList)){
            for (int i=0;i< strList.size();i++){
                String rowData = strList.get(i).trim();
                String[] rowDataArr=rowData.split("\\s+");
                if (rowDataArr!= null && rowDataArr.length == col){
                    for (int j=0;j < rowDataArr.length;j++) {
                        double value = Double.parseDouble(rowDataArr[j]);
                        doubleArr[i][j]= value;
                    }
                }

            }
        }
        return new Array2DRowRealMatrix(doubleArr);
    }
}
